#ifndef __ENCODER_H
#define __ENCODER_H
#include "main.h"
#include "usart.h"
#include "string.h"
#include <stdbool.h>
typedef struct
{

  uint8_t bSpeedErrorNumber;

  uint8_t bElToMecRatio;  /*!< Coefficient used to transform electrical to
                               mechanical quantities and viceversa. It usually
                               coincides with motor pole pairs number*/
  uint8_t SpeedUnit; /*!< The speed unit value is defined into mc_stm_types.h*/   
  
  uint8_t bMaximumSpeedErrorsNumber; /*!< Maximum value of not valid measurements
                                        before an error is reported.*/    
  int16_t hElAngle;

  int16_t hMecAngle;
  
  int32_t wMecAngle;

  int16_t hAvrMecSpeedUnit;

  int16_t hElSpeedDpp;
  int16_t InstantaneousElSpeedDpp;

  int16_t hMecAccelUnitP;
                            
  uint16_t hMaxReliableMecSpeedUnit; /*!< Maximum value of measured mechanical speed that is
                                        considered to be valid. Expressed
                                        in the unit defined by #SPEED_UNIT.*/
  uint16_t hMinReliableMecSpeedUnit; /*!< Minimum value of measured mechanical speed that is
                                        considered to be valid. Expressed
                                        in the unit defined by #SPEED_UNIT.*/
  uint16_t hMaxReliableMecAccelUnitP; /*!< Maximum value of measured acceleration
                                        that is considered to be valid. Expressed in
                                        the unit defined by #SPEED_UNIT */
  uint16_t hMeasurementFrequency;  /*!< Frequency at which the user will request
                                    a measurement of the rotor electrical angle. Expressed in PWM_FREQ_SCALING*Hz.
                                    It is also used to convert measured speed from the unit
                                    defined by #SPEED_UNIT to dpp and viceversa.*/
  uint32_t DPPConvFactor; /* (65536/PWM_FREQ_SCALING) */
  

} SpeednPosFdbk_Handle_t;

#define ENC_SPEED_ARRAY_SIZE  ((uint8_t)16)    /* 2^4 */

#define SPEED_UNIT 100
#define SPEED_LOOP_FREQUENCY_HZ       2000 /*!<Execution rate of speed
                                                      regulation loop (Hz) */



typedef struct
{
  SpeednPosFdbk_Handle_t _Super;
  
  TIM_TypeDef * TIMx;   /*!< Timer used for ENCODER sensor management.*/
  
  uint32_t SpeedSamplingFreqUnit; /*!< Frequency at which motor speed is to be
                                   computed. It must be equal to the frequency
                                   at which function SPD_CalcAvrgMecSpeedUnit
                                   is called.*/
  int32_t DeltaCapturesBuffer[ENC_SPEED_ARRAY_SIZE]; /*!< Buffer used to store
                                        captured variations of timer counter*/
                                        
  
  uint32_t U32MAXdivPulseNumber;       /*! <It stores U32MAX/hPulseNumber*/

  uint16_t SpeedSamplingFreqHz;        /*! <Frequency (Hz) at which motor speed
                                        is to be computed. */             
                                        
  /* SW Settings */
  uint16_t PulseNumber; /*!< Number of pulses per revolution, provided by each
                              of the two encoder signals, multiplied by 4 */
  
  volatile uint16_t TimerOverflowNb;    /*!< Number of overflows occurred since
                                        last speed measurement event*/
  uint16_t PreviousCapture;            /*!< Timer counter value captured during
                                        previous speed measurement event*/
 
  FunctionalState RevertSignal; /*!< To be enabled if measured speed is opposite
                                     to real one (ENABLE/DISABLE)*/

  uint8_t SpeedBufferSize; /*!< Size of the buffer used to calculate the average
                             speed. It must be <= 16.*/


  bool SensorIsReliable;            /*!< Flag to indicate sensor/decoding is not
                                         properly working.*/

  uint8_t ICx_Filter;                  /*!< Input Capture filter selection */

  volatile uint8_t DeltaCapturesIndex; /*! <Buffer index*/

  bool TimerOverflowError;              /*!< true if the number of overflow
                                        occurred is greater than 'define'
                                        ENC_MAX_OVERFLOW_NB*/

} ENCODER_Handle_t;


typedef struct
{
	int16_t isRun;
	int16_t Enable;
	uint32_t ErrorCode;
	uint32_t ErrorCnt;
	int32_t RotorDirection;
	int32_t OrigMecAngle17b;
	int32_t LastOrigMecAngle17b;
	int32_t OrigOutMecAngle20b;
	int32_t LastOrigOutMecAngle20b;
	int16_t Offset;
	int16_t Speed;
	int16_t Speed1;
	int16_t OrigSpeed;
	int32_t OrigSpeedFilter;
	int32_t ElectricalSpeed; //电机电角速度
	float FloatOrigSpeedFilter;
	int16_t SpeedFilter1KHz;
	int16_t SpeedFilter250Hz;
	int16_t posToSpeed;
	int16_t SpeedSwitch;
	int16_t PrevSpeed;
    int32_t InSingleData;
    int32_t OutSingleData;
    int32_t InMultiData;
    int32_t OutMultiData;
	int16_t InNumOfCircle;
	int16_t OutNumOfCircle;
	int16_t Temperature;
	int16_t AlignedMecAngle;
	int16_t MecAngle;
	int16_t ElAngle;
	int16_t PrevMecAngle;
	int16_t DiffMecAngle;
	int16_t MecAccel;
	int32_t Position;
	int32_t InPosition;
  int32_t OutPosition;
	int32_t PrevPosition;
  int32_t InOriPosition;
	int32_t DiffPosition;
	int32_t PositionCaptureBuf[100];
	int32_t TimDura_us;
    int32_t resolution_pos;
    int32_t scale_pos;
    int32_t resolution_vel;
    int32_t scale_vel;
    int32_t debug_data;
	uint8_t Status;
	uint8_t Crc8;
	uint8_t Recieved;
	uint8_t NoRecieved;
	uint8_t Crc8Result;
	uint8_t rx_buf[11];
  uint8_t tx_buf[1];
	uint16_t Txcnt;
	uint16_t Rxcnt;
	uint16_t RxCrccnt;
}Encoder_t;

extern Encoder_t Encoder;

typedef struct
{
    int32_t OutAccEcc;
}EncObserver_t;
extern EncObserver_t EncObserver;

typedef struct
{
	float fCurrentFilter1KHz;
	float fSpeedFilter1KHz;
	float fSpeedFilterFreq;
}
Filter_t;
extern Filter_t FilterCSP;



uint8_t calcCRC(uint8_t * buffer, uint8_t length);
int16_t ENC_CalcAngle( ENCODER_Handle_t * pHandle );
void ENC_SetMecAngle( ENCODER_Handle_t * pHandle, int16_t hMecAngle );
void encoder_init(void);
extern void encoder_tx(void);
extern void encoder_rx(void);
void encoder_rx_noprocess(void);

#endif
